﻿jQuery(function ($) {
	var $win = $(window),
		$doc = $(document),
		trigger;

	var updateTrigger = function () {
		trigger = $doc.height() - $win.height() - 200;
	},

	startChecking = function (e) {
		if ($win.scrollTop() > trigger) {
			$win.unbind('scroll', startChecking);
			loadPost();
		}
	},

	loadPost = function () {
		//prepare date for query
		// m/d/y ...
		var date = $('#MainColumn_QuestionList').children(':last').find('.date').text();
		var months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
		var m = date.match(/^(\d{1,2})\//)[1]; //get month value
		var d = date.match(/\/(\d{1,2})\//)[1]; //get day
		date = date.replace(/\/\d{1,2}\//, ' ' + months[m - 1] + ' '); //replace month
		date = date.replace(/^\d{1,2}/, d); //replace day
		date = date.replace(/(am|pm)/i, '');

		//var date = encodeURI($('#MainColumn_QuestionList').children(':last').find('.date').text());
		//var months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
		//var m = date.match(/\/(\d{2})\//)[1];
		//date = date.replace(/\/\d{2}\//, ' ' + months[m - 1] + ' ');
		//date = date.replace(/(am|pm)/i, '');

		//get subjects
		var subjects = location.search.match(/subjects=\d+/ig);
		var newSubs = [];
		if (subjects) { //subjects in location
			for (var i = 0; i < subjects.length; i++) {
				newSubs.push(subjects[i].match(/subjects=(\d+)/)[1]);
			}
		} else {
			//user's subjects
			$('#menu td a').each(function () {
				newSubs.push(this.href.match(/subjects=(\d+)/i)[1]);
			});
		}
		subjects = newSubs.join(',');

		//get rating
		var rating = location.search.match(/rating=(\d+)/i);
		rating = rating ? rating[1] : '0';

		//query server
		var data = '{limit: 10, rating:' + rating + ', from: "' + date + '", subjects: [' + subjects + ']}';
		$.ajax({
			type: 'post',
			data: data,
			url: baseUrl + '/Services/QuestionService.asmx/List',
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (response, success) {
				if (success === 'success') {
					appendQuestion(response.d);
					if (response.d > 0) {
						$win.scroll(startChecking);
					}
				} else {
					alert('Failed to delete question.');
				}
			}
		});
	},

	appendQuestion = function (list) {
		var canDelete = $('body div[id=ud]:first input').length === 4;
		var userId = $('#MainColumn_userId').val();
		for (var i = 0; i < list.length; i++) {
			var getValue = function (name) {
				var t = list[i][name];
				return t;
			},
			tmpl = $('#question-template').html(),
			data = {
				id: getValue('Id'),
				title: getValue('Title'),
				content: getValue('Content'),
				date: formatDate(getValue('DateTimeUpdated')),
				user: getValue('UserName'),
				subject: getValue('SubjectId'),
				rating: getValue('Rating'),
				answers: getValue('Answers'),
				haveDeleteBtn: canDelete,
				haveEditBtn: userId == getValue('UserId')
			};
			$(Mustache.to_html(tmpl, data)).appendTo('#MainColumn_QuestionList');
		}
		updateTrigger();
	},

	formatDate = function (date) {
		//d/m/y h:mm:s amORpm
		var d = eval('new ' + date.substr(1, date.length - 2)), //timestamp to date
		hours = d.getHours(),
		minutes = d.getMinutes(),
		amOrPm = hours >= 12 ? 'PM' : 'AM';
		hours = hours > 12 ? hours - 12 : hours;
		if ((minutes + '').length === 1) {
			minutes = '0' + minutes;
		}

		date = d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear() + ' ' + hours + ':' + minutes + ':' + d.getSeconds() + ' ' + amOrPm;

		return date;
	}

	$win.scroll(startChecking).resize(updateTrigger).resize();

});